from flask import session, redirect, url_for, flash, render_template, request
from flask_login import login_user, login_required, logout_user, current_user
from app import db
from app.auth.forms import LoginForm, RegisterForm, UpdatePwdForm, UpdateEmail, ResetPassword, SendResetPassword
from app.main.mail import send_mail
from app.models import UserInfo
from . import auth


# 登录
@auth.route("/login/", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = UserInfo.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data) and user.confirmed:
            login_user(user, form.remember_me.data)
            next = request.args.get("next")
            if next is None or not next.startwith('/'):
                next = url_for('main.index')
            return redirect(next)
        else:
            flash("用户名或密码错误")
    return render_template('auth/login.html', form=form)


# 注册
@auth.route('/register/', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = UserInfo(username=form.username.data, sex=form.sex.data, email=form.email.data)
        user.password = form.password.data
        db.session.add(user)
        try:
            db.session.commit()
            token = user.generate_confirmation_token()
            send_mail(user.email, '激活账号', 'mail/confirm', user=user, token=token)
            flash("邮件已发送到您的邮箱，请及时激活账号!!!")
            return redirect(url_for("auth.login"))
        except Exception as e:
            print(e.args)
            db.session.rollback()
            flash("用户已存在")
    return render_template("auth/register.html", form=form)


# 登出
@auth.route('/logout/')
@login_required
def logout():
    logout_user()
    flash('成功注销登录')
    return render_template(url_for('main.index'))


# 邮箱激活账号
@auth.route('/confirm/')
def confirm():
    token = request.args.get("token")
    username = request.args.get("username")
    user = UserInfo.query.filter_by(username=username).first()
    if user.confirmed:
        flash("该账号已激活")
        return redirect(url_for("auth.login"))
    if user.confirm(token):
        db.session.commit()
        flash("您已成功激活您的账号")
    else:
        flash("激活码失效或已过期")
    return redirect(url_for("auth.login"))


# 修改密码
@auth.route('/update_password/', methods=['GET', 'POST'])
@login_required
def update_password():
    form = UpdatePwdForm()
    if form.validate_on_submit():
        form.update_pwd()
        return redirect(url_for("auth.login"))
    return render_template('auth/update_password.html', form=form)


# 更新邮箱
@auth.route('/update_email/', methods=["GET", "POST"])
@login_required
def update_email():
    form = UpdateEmail()
    if form.validate_on_submit():
        token = current_user.generate_confirmation_token()
        send_mail(form.new_email.data, "更新邮箱", 'mail/update_email', user=current_user, email=form.new_email.data,
                  tonken=token)
    return render_template("auth/update_email.html", form=form)


# 确认修改邮箱
@auth.route('/send/update_email/')
def validate_email():
    token = request.args.get("token")
    user = current_user
    if user.confirm(token):
        user.email = request.args.get("email")
        db.session.add(user)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
        flash("邮箱修改成功")
    else:
        flash("激活码失效或已过期")
    return redirect(url_for("main.index"))


# 重置密码
@auth.route('/reset_pwd/', methods={"GET", 'POST'})
def reset_pwd():
    form = ResetPassword()
    if form.validate_on_submit():
        user = UserInfo.query.filter_by(email=form.email.data).first()
        token = user.generate_confirmation_token()
        send_mail(form.email.data, '重置密码', 'mail/reset_pwd', user=user, token=token)
    return render_template('auth/reset_pwd.html', form=form)


# 邮箱重置密码
@auth.route('/send/reset_pwd/', methods={"GET", 'POST'})
def send_reset_pwd():
    email = request.args.get("email")
    token = request.args.get("token")
    user = UserInfo.query.filter_by(email=email).first()
    form = SendResetPassword()
    if user.confirm(token):
        if form.validate_on_submit():
            user.password = form.new_password.data
            db.session.add(user)
            try:
                db.session.commit()
                flash("密码修改成功")
                return redirect(url_for("auth.login"))
            except Exception as e:
                db.session.rollback()
    else:
        flash("激活码失效或已过期")
    return render_template('auth/reset_pwd.html', form=form)
